//
//  OverviewController.swift
//  SCA
//
//  Created by tjun on 2025/9/7.
//

import UIKit


class TotalRevenueView: UIView {
    
    let titleLabel = UILabel(text: "总收益".localizedString, font: UIFontMediumMake(12), textColor: .white)
    let valueLabel = UILabel(text: "$0.00", font: UIFontSemiboldMake(30), textColor: .white)
    let extractRecordsButton = UIButton(type: .system)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        titleLabel.addTo(self)
        titleLabel.snp.makeConstraints { make in
            make.top.left.equalToSuperview()
        }
        
        valueLabel.addTo(self)
        valueLabel.snp.makeConstraints { make in
            make.left.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(2)
        }
        
        extractRecordsButton.addTo(self)
        extractRecordsButton.setImage(UIImage(named: "extractRecords"), for: .normal)
        extractRecordsButton.snp.makeConstraints { make in
            make.width.height.equalTo(30)
            make.right.equalToSuperview()
            make.centerY.equalTo(valueLabel)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



class OverviewController: BaseController {
    
    private let energyView = EnergySliderView()
    private let totalRevenueView = TotalRevenueView()
    private let powerInfo = PowerInfoView()
    private let powerCircleView = PowerCircleView()
    private let powerValueView = PowerValueView()
    
    private var scrollView: UIScrollView!
    private var contentView: UIView!
    private let bottomStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.spacing = 10
        stackView.alignment = .center
        stackView.distribution = .fill   // 宽度自适应子控件总和
        return stackView
    }()
    
    let realSize: CGSize
    
    init(realSize: CGSize) {
        self.realSize = realSize
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: realSize.width, height: realSize.height)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        let contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        scrollView.contentSize = contentSize
        
        contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
        
        
        let gifView = FLAnimatedImageView()
        gifView.contentMode = .scaleAspectFit
        gifView.runLoopMode = .common
        gifView.animationDuration = 0.25
        
        let bannerLeftRightMargin = 20
        let bannerH = (Int(view.width) - bannerLeftRightMargin * 2) * 518 / 1179
        contentView.addSubview(gifView)
        gifView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(bannerLeftRightMargin)
            make.top.equalTo(5)
            make.height.equalTo(bannerH)
        }
        
        if let path = Bundle.main.path(forResource: "bg-skate-dark", ofType: "gif"),
           let data = try? Data(contentsOf: URL(fileURLWithPath: path)), let animatedImage = FLAnimatedImage(animatedGIFData: data) {
            animatedImage.loopCount = 0
            gifView.animatedImage = animatedImage
        }
        
        powerCircleView.addTo(contentView)
        powerCircleView.setCenterText(top: "算力".localizedString, value: "0.00", unit: "G")
        powerCircleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(50)
            make.width.equalTo(146)
            make.top.equalTo(gifView.snp.bottom).offset(10)
            make.height.equalTo(146.scaled)
        }
        
        powerValueView.addTo(contentView)
        powerValueView.snp.makeConstraints { make in
            make.left.equalTo(powerCircleView.snp.right).offset(50)
            make.right.equalTo(-AppStyle.margin.left)
            make.top.equalTo(powerCircleView)
            make.height.equalTo(powerCircleView)
        }
        
        let castingButton = MainButton(type: .system, title: "熔铸算力".localizedString, font: UIFontSemiboldMake(16), textColor: .white).addTo(contentView)
        castingButton.addTarget(self, action: #selector(castingButtonTapped), for: .touchUpInside)
        castingButton.snp.makeConstraints { make in
            make.top.equalTo(powerCircleView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.width.equalTo(222)
            make.height.equalTo(36)
        }
        
        powerInfo.backgroundColor = UIColorMake(0x2E323F)
        powerInfo.addCorner(radius: 10)
        contentView.addSubview(powerInfo)
        powerInfo.onPowerRowViewInfoTapped = {[weak self] powerModel in
            guard let weakSelf = self else { return }
            
            MessageAlertController(text: powerModel.info).showIn(weakSelf)
        }
        
        powerInfo.snp.makeConstraints { make in
            make.top.equalTo(castingButton.snp.bottom).offset(18)
            make.left.right.equalToSuperview().inset(20)
            make.height.equalTo(152)
        }
        
        energyView.addTo(contentView)
        energyView.onInfoButtonTapped = {[weak self] in
            guard let weakSelf = self else { return }
            
            MessageAlertController(text: """
计算方式：EV值 = 配套总额 × 3.2。例如，购买1000元配套，EV值为3200元。\n收益跟踪：每次获得收益后，EV值将逐渐减少，实时反映剩余收益潜力。\n复投提示：当EV值降至初始值的10%（如3200元降至320元）时，您需要复投新配套以继续获得收益。\n投资价值：EV值基于我们优化的算力收益模型，确保透明、高效的回报。
""", paragraphSpacing: 10).showIn(weakSelf)
        }
        
        energyView.snp.makeConstraints { make in
            make.top.equalTo(powerInfo.snp.bottom).offset(30)
            make.left.right.equalToSuperview().inset(20)
            make.height.equalTo(60)
        }
        
        energyView.maxValue = 640
        energyView.currentValue = 502
        
        totalRevenueView.addTo(contentView)
        totalRevenueView.extractRecordsButton.addTarget(self, action: #selector(earningsRecordButtonTapped), for: .touchUpInside)
        totalRevenueView.snp.makeConstraints { make in
            make.top.equalTo(energyView.snp.bottom).offset(6)
            make.left.right.equalToSuperview().inset(20)
            make.height.equalTo(64)
        }
        
        let receiveButton = GradientButton(type: .system, title: "领取".localizedString, font: UIFontMediumMake(12), textColor: .white, target: self, action: #selector(receiveButtonTapped(_ :)))
        receiveButton.colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
        receiveButton.locations = [0, 0.66, 1]
        receiveButton.setStartPoint(CGPoint(x: 0, y: 0.5), endPoint: CGPointMake(1, 0.5))
        receiveButton.isGradientBorder = true
        receiveButton.borderWidth = 1
        receiveButton.cornerRadius = 5
        receiveButton.addTo(contentView)
        receiveButton.snp.makeConstraints { make in
            make.width.equalTo(75)
            make.height.equalTo(26)
        }
        
        let convertButton = GradientButton(type: .system, title: "转换 USCA".localizedString, font: UIFontMediumMake(12), textColor: .white, target: self, action: #selector(convertButtonTapped(_ :)))
        convertButton.colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
        convertButton.locations = [0, 0.66, 1]
        convertButton.setStartPoint(CGPoint(x: 0, y: 0.5), endPoint: CGPointMake(1, 0.5))
        convertButton.isGradientBorder = true
        convertButton.borderWidth = 1
        convertButton.cornerRadius = 5
        convertButton.addTo(contentView)
        convertButton.snp.makeConstraints { make in
            make.width.equalTo(85)
            make.height.equalTo(26)
        }
        
        bottomStackView.addArrangedSubview(receiveButton)
        bottomStackView.addArrangedSubview(convertButton)
        bottomStackView.addTo(contentView)
        bottomStackView.snp.makeConstraints { make in
            make.top.equalTo(totalRevenueView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
        }
        
        let swapTipLabel = UILabel(text: "*0% 熔炉基金".localizedString, font: UIFontMake(10), textColor: .white).addTo(contentView)
        swapTipLabel.snp.makeConstraints { make in
            make.top.equalTo(bottomStackView.snp.bottom).offset(5)
            make.centerX.equalTo(convertButton)
        }
        
        updateContentSize()
        
        let currentUserInfoModel = UserInfoModel.current
        
        energyView.maxValue = (currentUserInfoModel.ev as NSString).doubleValue
        energyView.currentValue = (currentUserInfoModel.evBalance as NSString).doubleValue
        
        NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: NotificationName.buyPowerSucceed, object: nil)
        
        loadData()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func loadData() {
        ComputingPowerService.loadPersonalPowerOverviewData { powerInfo in
            self.powerCircleView.powerInfo = powerInfo
            self.powerValueView.powerInfo = powerInfo
            self.powerInfo.powerInfo = powerInfo
        }
        
        ComputingPowerService.loadBonusClaimOverviewData { value in
            self.totalRevenueView.valueLabel.text = value
        }
    }
    
    @objc func earningsRecordButtonTapped() {
        let earningsRecordController = ExtractRecordsController()
        navigationController?.pushViewController(earningsRecordController, animated: true)
    }
    
    @objc func convertButtonTapped(_ button: UIButton) {
        let coinConvertController = CoinConvertController()
        coinConvertController.title = button.currentTitle
        topNavigationController()?.pushViewController(coinConvertController, animated: true)
    }
    
    @objc func receiveButtonTapped(_ button: UIButton) {
        let receiveAwardController = ReceiveAwardController()
        receiveAwardController.title = button.currentTitle
        topNavigationController()?.pushViewController(receiveAwardController, animated: true)
    }
    
    @objc func castingButtonTapped() {
        let purchasePowerListController = PurchasePowerListController()
        topNavigationController()?.pushViewController(purchasePowerListController, animated: true)
    }
    
    
    private func updateContentSize() {
        
        contentView.setNeedsLayout()
        contentView.layoutIfNeeded()
        
        let contentSize = CGSizeMake(view.width, bottomStackView.maxY + 30 + tabBarSafeBottomMargin)
        scrollView.contentSize = contentSize
        contentView.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
    }
    
    override var hiddenNavigationBar: Bool {
        return true
    }
    
}
